package com.aj.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

    public static int getAge(Long ts) {
        // Date date_now = new Date();
        // Date date_age = new Date(ts);

        Calendar date_now = Calendar.getInstance();
        Calendar date_age = Calendar.getInstance();
        date_age.setTimeInMillis(ts);

        int ageYear = date_now.get(Calendar.YEAR) - date_age.get(Calendar.YEAR);
        int ageMonth = date_now.get(Calendar.MONTH) - date_age.get(Calendar.MONTH);
        int ageDate = date_now.get(Calendar.DATE) - date_age.get(Calendar.DATE);
        // 如果年月都大约0证明满了一岁了
        if (ageYear >= 0 && ageMonth > 0) {
            return ageYear;
        }
        if (ageYear >= 0 && ageMonth < 0) {
            return (ageYear - 1);
        }
        // 如果年日都大约0证明满了一岁了
        if (ageYear >= 0 && ageMonth == 0 && ageDate >= 0) {
            return ageYear;
        }
        if (ageYear >= 0 && ageMonth == 0 && ageDate < 0) {
            return (ageYear - 1) < 0 ? 0 : (ageYear - 1);
        }
        return ageYear < 0 ? 0 : ageYear;
    }

    public static long getTime(String dateString) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = simpleDateFormat.parse(dateString);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }

}
